<!--文件上传组件-->
<template>
  <div class="upload-file">
    <el-upload
        ref="fileUpload"
        v-if="props.type === 'default'"
        :action="baseURL + other.adaptationUrl(props.uploadFileUrl)"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
        :headers="headers"
        :disabled="self_disabled"
        :accept="fileType"
        :limit="limit"
        :on-error="handleUploadError"
        :on-remove="handleRemove"
        :on-preview="handlePreview"
        :data="formData"
        :auto-upload="autoUp"
        :on-success="handleUploadSuccess"
        class="upload-file-uploader"
        drag
        multiple
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        {{ $t('excel.operationNotice') }}
        <em>{{ $t('excel.clickUpload') }}</em>
      </div>

      <template #tip>
        <div class="el-upload__tip" v-if="props.isShowTip">
          {{ $t('excel.pleaseUpload') }}
          <template v-if="props.fileSize">
            {{ $t('excel.size') }} <b style="color: #f56c6c">{{ props.fileSize }}MB</b></template
          >
          <template v-if="props.fileType">
            {{ $t('excel.format') }} <b style="color: #f56c6c">{{ props.fileType.join('/') }}</b>
          </template>
          {{ $t('excel.file') }}
        </div>
        <div v-if="props.filerType === 'property'" class="iput">
          <div>
            <span>对接人</span>
            <el-input v-model="user.contactBy" clearable></el-input>
          </div>
          <div>
            <span>联系电话 </span>
            <el-input v-model="user.contactNumber" clearable></el-input>
          </div>
        </div>
      </template>
    </el-upload>
    <el-upload
        ref="fileUpload"
        v-if="props.type === 'simple'"
        :action="baseURL + other.adaptationUrl(props.uploadFileUrl)"
        :before-upload="handleBeforeUpload"
        :disabled="self_disabled"
        :file-list="fileList"
        :headers="headers"
        :limit="limit"
        :auto-upload="autoUp"
        :on-error="handleUploadError"
        :on-remove="handleRemove"
        :data="formData"
        :on-success="handleUploadSuccess"
        class="upload-file-uploader"
        multiple
    >
      <el-button type="primary" link>{{ $t('excel.clickUpload') }}</el-button>
    </el-upload>
    <div v-if="props.filerType === 'property'" style="display: flex;justify-content: end">
      <el-button class="ml-3" type="success" @click="submitUpload">
        上传
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts" name="upload-file">
import {useMessage} from '/@/hooks/message';
import {Session} from '/@/utils/storage';
import other from '/@/utils/other';
import {useI18n} from 'vue-i18n';
const props = defineProps({
  modelValue: [String, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 200,
  },
  disabled: {
    type: Boolean,
    default: false
  },
  fileType: {
    type: Array,
    default: () => ['png', 'jpg', 'jpeg', 'doc', 'xls', 'ppt', 'txt', 'pdf', 'docx', 'xlsx', 'pptx'],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true,
  },
  uploadFileUrl: {
    type: String,
    default: '/admin/ra-file/upload',
  },
  type: {
    type: String,
    default: 'default',
    validator: (value: string) => {
      return ['default', 'simple'].includes(value);
    },
  },
  filerType:{
    type: String,
  },
  data: {
    type: Object,
    default: {}
  },
  dir: {
    type: String,
    default: ''
  },
  autoUpload: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['update:modelValue', 'change']);

const number = ref(0);
const fileList = ref([]) as any;
const uploadList = ref([]) as any;
const fileUpload = ref();
const {t} = useI18n();

// 判断是否禁用上传和删除
const self_disabled = computed(() => {
  return props.disabled
});

// 请求头处理
const autoUp = computed(() => {
  return props.filerType !== 'property';
});

// 请求头处理
const headers = computed(() => {
  return {
    Authorization: 'Bearer ' + Session.get('token'),
    'TENANT-ID': Session.getTenant(),
  };
});

// 请求参数处理
const formData = computed(() => {
  if(props.filerType === 'property'){
    return Object.assign(props.data, {dir: props.dir}, user);
  }else {
    return Object.assign(props.data, {dir: props.dir});
  }

});

// 上传前校检格式和大小
const handleBeforeUpload = (file: File) => {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.');
    const fileExt =  fileName[fileName.length - 1].toLocaleLowerCase();
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      useMessage().error(`${t('excel.typeErrorText')} ${props.fileType.join('/')}!`);
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      useMessage().error(`${t('excel.sizeErrorText')} ${props.fileSize} MB!`);
      return false;
    }
  }
  number.value++;
  return true;
};

// 上传成功回调
function handleUploadSuccess(res: any, file: any) {
  if (res.code === 0) {
    uploadList.value.push({
      name: file.name,
      url: res.data.url,
      fileUrl: res.data.fileName,
      fileSize: file.size,
      fileName: file.name,
      fileType: file.raw.type
    });
    uploadedSuccessfully();
  } else {
    number.value--;
    useMessage().error(res.msg);
    fileUpload.value.handleRemove(file);
    uploadedSuccessfully();
  }
}

// 上传结束处理
const uploadedSuccessfully = () => {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
    uploadList.value = [];
    number.value = 0;
    emit('change', listToString(fileList.value));
    emit('update:modelValue', listToString(fileList.value));
  }
};

const handleRemove = (file: any) => {
  fileList.value = fileList.value.filter((f) => !(f === file.url));
  fileList.value = []
  emit('change', listToString(fileList.value));
  emit('update:modelValue', listToString(fileList.value));
};

const handlePreview = (file: any) => {
  other.downBlobFile(file.url, {}, file.name);
};

/**
 * 将对象数组转为字符串，以逗号分隔。
 * @param list 待转换的对象数组。
 * @param separator 分隔符，默认为逗号。
 * @returns {string} 返回转换后的字符串。
 */
const listToString = (list: { url: string }[], separator = ','): string => {
  let strs = '';
  separator = separator || ',';
  for (let i in list) {
    if (list[i].url) {
      strs += list[i].url + separator;
    }
  }
  return strs !== '' ? strs.substr(0, strs.length - 1) : '';
};

const handleUploadError = () => {
  useMessage().error('上传文件失败');
};

/**
 * 监听 props 中的 modelValue 值变化，更新 fileList。
 */
watch(
    () => props.modelValue,
    (val) => {
      if (val) {
        let temp = 1;
        // 首先将值转为数组
        const list = Array.isArray(val) ? val : props?.modelValue?.split(',');
        // 然后将数组转为对象数组
        fileList.value = list.map((item) => {
          if (typeof item === 'string') {
            item = {name: item, url: item};
          }
          item.uid = item.uid || new Date().getTime() + temp++;
          return item;
        });
      } else {
        fileList.value = [];
        return [];
      }
    },
    {deep: true, immediate: true}
);

const submit = () => {
  fileUpload.value.submit();
};
const user= reactive({contactNumber:"",contactBy:''})
const submitUpload = () =>{
  var isPhone = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
  if (!isPhone.test(formData.value.contactNumber)) {
    useMessage().error('请输入正确的手机号码');
  } else {
    submit()
  }
}
defineExpose({
  submit,
});
</script>
<style lang="scss" scoped>
.iput{
 >div{
   display: flex;
   margin: 5px;
   >span  {
     display: flex;
     justify-content: center;
     align-items: center;
     width: 120px;
   }
 }
}
</style>